import {AiGlobalConfig} from "../AiGlobalConfig.ts";
import {AiImageConfig} from "./AiImageConfig.ts";
import {AiResponseListener} from "./AiResponseListener.ts"
import {InnerEditor} from "../../core/AiEditor.ts";
import { AiClient } from "./AiClient.ts";

export abstract class AiImage {

    public editor: InnerEditor;
    public globalConfig: AiGlobalConfig;
    public aiImageName: string;
    public aiImageConfig?: AiImageConfig;

    protected constructor(editor: InnerEditor, globalConfig: AiGlobalConfig, aiImageName: string) {
        this.editor = editor;
        this.globalConfig = globalConfig;
        this.aiImageName = aiImageName;
        this.aiImageConfig = globalConfig.images?.[aiImageName];
    }
    
    draw(selectedText: string, prompt: string, listener: AiResponseListener): void {
        const onSuccess = (url: string) => {
            const aiClient = this.createAiClient(url, listener);
            const finalPrompt = prompt.includes("{content}") ? prompt.split('{content}').join(selectedText) : `${selectedText ? selectedText + "\n" : ""}${prompt}`
            const payload = this.wrapPayload(finalPrompt);
            aiClient.start(typeof payload === "string" ? payload : JSON.stringify(payload))
        }

        onSuccess(this.createAiClientUrl())
    }

    abstract createAiClientUrl(): string;

    /**
     * 创建客户端
     */
    abstract createAiClient(url: string, listener: AiResponseListener): AiClient;

    /**
     * 封装消息，把 prompt 转换为协议需要的格式
     * @param prompt
     */
    abstract wrapPayload(prompt: string): any;
}